<template>
  <div class="form-rules-container layout-pd" style="text-align: left">
    <el-form :model="queryRuleForm" inline>
      <el-form-item label="规格名称">
        <el-input v-model="queryRuleForm.ruleName" placeholder="请输入规格名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="ruleSearch">搜索</el-button>
        <el-button @click="queryRuleForm = {}">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="handleOpen">添加规格</el-button>
        <el-button type="danger" @click="handleOpen">批量删除</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="规格名称" prop="ruleName"></el-table-column>
      <el-table-column label="商品规格" prop="rule"></el-table-column>
      <el-table-column label="商品属性" prop="ruleAttr"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOpen(scope.row)">修改</el-button>
          <el-button link type="primary" size="small" @click="delRule(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
    />
    <el-dialog v-model="dialogVisible" title="属性规格" width="50%">
      <el-form :model="ruleForm" label-width="100" :rules="rules">
        <el-form-item label="规格名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="填写规格名称"/>
        </el-form-item>
        <template v-for="(item, index) in ruleValue" :key="item">
          <!-- 判断是否为添加新规格 -->
          <div v-if="item.editFlag" style="display: flex;">
            <el-form-item label="规格">
              <el-input style="width: 150px;" v-model="item.value" placeholder="规格"></el-input>
            </el-form-item>
            <el-form-item label="规格值">
              <el-input style="width: 150px;" v-model="item.detail" placeholder="规格值"></el-input>
            </el-form-item>
            <el-button type="primary" @click="setItemRule(index, item)">确定</el-button>
            <el-button type="info" @click="cancelItemRule(index, item)" plain>取消</el-button>
          </div>
          <!-- 添加新规格值 -->
          <div v-else style="display: flex;">
            <el-form-item label=" ">
              <el-row>
                <!-- 显示商品规格 -->
                <el-col :span="24">
                  <el-text>
                    {{ item.value }}
                    <el-icon>
                      <CircleClose/>
                    </el-icon>
                  </el-text>
                </el-col>
                <!-- 显示规格值 -->
                <el-col :span="24">
                  <el-tag v-for="tag in item.detail"
                          @close="handleTagClose(tag, item)" :key="tag" closable
                          :type="tag.type" style="margin-right: 5px;">
                    {{ tag }}
                  </el-tag>
                  <!-- 添加规格值 -->
                  <el-input v-model="item.addDetail"
                            style="width: 70px;"
                            v-if="item.addFlag"
                            placeholder=""
                            @blur="saveDetail(item)"></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="addDetail(item)">
                    + 添加
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </template>
        <!-- 添加商品规格按钮，动态添加html代码 -->
        <el-col :span="24">
          <el-button type="primary" @click="addRuleValue" v-if="isShow">添加新规格</el-button>
        </el-col>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">提交</el-button>
			</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
// 引入axios
const axios = getCurrentInstance().appContext.config.globalProperties.$axios;
// 响应式数据对象
const multipleSelection = ref([])
const queryRuleForm = ref({})
const tableData = ref([])
const ruleValue = ref([])
const ruleForm = ref({})
const dialogVisible = ref(false)
const isShow = ref(true)
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(20)
// 表单验证
const rules = {
  ruleName: [{ required: true, message: '请输入规格名称', trigger: 'blur' }]
}
// 复选框
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id)
}
// 添加规格
const addRuleValue = () => {
  ruleValue.value.push({ value: '', detail: [], editFlag: true })
  isShow.value = false
}
// 添加规格值，点击确定时将填写的数据替换到ruleValue数组中
const setItemRule = (index, item) => {
  item.editFlag = false
  ruleValue.value.push({
    value: item.value,
    detail: [item.detail],
    editFlag: false
  })
  ruleValue.value.splice(index, 1)
  isShow.value = true
}
// 取消添加规格
const cancelItemRule = (index, item) => {
  item.editFlag = false
  ruleValue.value.splice(index, 1)
  isShow.value = true
}
// 添加规格值
const addDetail = (item) => {
  item.addDetail = ''
  item.addFlag = true
}
// 保存属性值
const saveDetail = (item) => {
  console.log(item)
  item.detail.push(item.addDetail)
  item.addFlag = false
}
// 删除规格值
const handleTagClose = (tag, item) => {
  item.detail = item.detail.filter(obj => obj !== tag)
  // 将字符串转成json对象，JSON.stringify将对象转换成字符串
  JSON.parse(JSON.stringify(item))
}

// 打开编辑窗口
const handleOpen = (row) => {
  dialogVisible.value = true
  if (row.id) {
    console.log(row)
    ruleValue.value = row.ruleValue
    ruleForm.value = row
  } else {
    ruleValue.value = []
    ruleForm.value = {}
  }
}
// 搜索商品规格
const ruleSearch = async () => {
  const params = { ...queryRuleForm.value, pageNum: pageNum.value, pageSize: pageSize.value }
  // 请求后台获取数据
  let res = await axios.post('/rule/pageList', params);
  // 设置数据回显
  tableData.value = res.data.data.records;
  total.value = res.data.data.total
  pageNum.value = res.data.data.current
  // 循环获取规格名称，规格值
  for (let i = 0; i < tableData.value.length; i++) {
    // 赋值给tableData
    tableData.value[i] = {
      id: tableData.value[i].id,
      ruleName: tableData.value[i].ruleName,
      ruleValue: JSON.parse(tableData.value[i].ruleValue),
      rule: JSON.parse(tableData.value[i].ruleValue).map(v => v.value).join(','),
      ruleAttr: JSON.parse(tableData.value[i].ruleValue).map(v => v.detail.join(',')),
    }
  }
}
// 编辑商品规格
const submitForm = async () => {
  ruleForm.value.ruleValue = ruleValue.value
  // 判断是修改还是新增
  if (ruleForm.value.id) {
    await axios.put('/rule', ruleForm.value)
    ElMessage.success("修改成功")
    dialogVisible.value = false
    await ruleSearch()
  } else {
    let res = await axios.post('/rule', ruleForm.value)
    if (res.data.code === "1") {
      ElMessage.success("新增成功")
      dialogVisible.value = false
      await ruleSearch()
    } else {
      ElMessage.error(res.msg);
    }
  }
}
// 删除商品规格
const delRule = async (id) => {
  await axios.delete(`/rule/${id}`)
  ElMessage.success('删除成功')
  await ruleSearch()
}
onMounted(ruleSearch)

</script>
